package com.one.square.oauth.mobile;

import cn.hutool.core.util.StrUtil;
import com.one.square.core.constant.SecurityConstants;
import com.one.square.core.exception.BizException;
import com.one.square.oauth.service.impl.OneSquareUserDetailsServiceImpl;
import lombok.Data;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.HashSet;

/**
 * @author cwm
 * @Description 短信验证码认证授权提供者
 * @date 2021/10/21 下午5:14
 * @Version 1.0
 */
@Data
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {
    private UserDetailsService userDetailsService;
    private StringRedisTemplate redisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String code = (String) authenticationToken.getCredentials();
        String codeKey = SecurityConstants.SMS_CODE_PREFIX + mobile;
        String correctCode = redisTemplate.opsForValue().get(codeKey);
        // 验证码比对
        if (StrUtil.isBlank(correctCode) || !code.equals(correctCode)) {
            throw new BizException("验证码不正确");
        } else {
            redisTemplate.delete(codeKey);
        }

        UserDetails userDetails = ((OneSquareUserDetailsServiceImpl) userDetailsService).loadUserByMobile(mobile);
        SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken(userDetails, new HashSet<>());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
